/* #include "linux-rbtree.h" */
#include "linux-rbtree.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

struct RbNode {
    int key;
    struct rb_node rb_node;
    int value;
};

static inline int comare_fn(const struct rb_node *n1, const struct rb_node *n2) {
    const struct RbNode *x = rb_entry(n1, struct RbNode, rb_node);
    const struct RbNode *y = rb_entry(n2, struct RbNode, rb_node);
    return x->key - y->key;
}

int main() {

    struct rb_root root;
    root.rb_node = NULL;

    struct RbNode dummy;
    dummy.key = 100;
    struct rb_node *res = NULL;
    rb_node_find(&root, &dummy.rb_node, comare_fn, res);
    assert(res);
    struct RbNode *ev = rb_entry(res, struct RbNode, rb_node);
    assert(ev->key == dummy.key);


    struct RbNode *r;
    for (int i = 0; i < 100; i++) {
        r = malloc(sizeof(struct RbNode));
        r->key = i + 1;
        /* r->value = 0; */
        struct rb_node *duplicate_node;
        rb_node_add(&r->rb_node, &root, comare_fn , duplicate_node);
        assert(duplicate_node == NULL);
    }

    rb_erase(&r->rb_node, &root);

    dummy.key = 100;

    rb_node_find(&root, &dummy.rb_node, comare_fn, res);
    assert(res);
    ev = rb_entry(res, struct RbNode, rb_node);
    assert(ev->key == dummy.key);
    printf("%d\n", ev->key);
}
